<!--
 * Copyright © 2022 XXXXXXXXX
 * @Author: zhangxiang
 * @Date: 2022-06-06 15:03:23
 * @LastEditors: zhangxiang
 * @LastEditTime: 2022-10-31 17:43:38
 * @Description:
 *
-->

<template>
  <div class="usercenter-ctn">
    <template v-if="!isLogin">
      <el-link @click="login">登录</el-link>
    </template>
    <template v-else>
      <el-dropdown size="medium">
        <div class="name">
          {{ userName }}<i class="arrow-down el-icon-arrow-down"></i>
        </div>
        <el-dropdown-menu slot="dropdown">
          <router-link to="/">
            <el-dropdown-item>首页</el-dropdown-item>
          </router-link>
          <el-dropdown-item
            divided
            @click.native="logoutClick"
          ><div>退出登录</div></el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </template>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { isEmptyString } from '@/utils/index'
import { logout } from '@/api/user'

export default {
  name: 'UserCenter', // 组件名称
  data() {
    return {}
  },
  computed: {
    /**
     * @description: 用户名
     * @return {*}
     */
    ...mapGetters(['userName']),
    /**
     * @description: 是否登录
     * @return {*}
     */
    isLogin() {
      return !isEmptyString(this.userName) // 用户名不为空
    }
  },
  created() {},
  methods: {
    /**
     * @description: 登录 按钮
     * @return {*}
     */
    login() {
      // 路由去登录
      this.$router.replace({
        path: `/login?redirect=${this.$route.path}`, // 带上重定向路径
        query: this.$route.query // 带上参数
      })
    },
    /**
     * @description: 登出 按钮
     * @return {*}
     */
    logoutClick() {
      // 弹窗
      this.$confirm('确定退出登录吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        logout() // 登出
        setTimeout(() => {
          // store 重置状态
          this.$store.dispatch('user/resetState').then(() => {
            // 成功后去登录页面
            this.$router.replace({
              path: '/login'
            })
          })
        }, 300)
      })
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/assets/css/common.less";
.usercenter-ctn {
  .name {
    .textStyle(14px, 500, #4a4a4a);
    cursor: pointer;
  }

  .arrow-down {
    margin-left: 6px;
    color: #4a4a4a;
  }
}
</style>
